﻿using System;

namespace EpiNEXT.Services.Validation.Functions
{
    public sealed class Round : FunctionBase
    {
        public Round()
            : base()
        {
        }

        public override object Execute(Record record)
        {
            if (Parameters.Count == 0)
            {
                return null;
            }
            else if (Parameters.Count == 1)
            {
                decimal d;

                bool success = Decimal.TryParse(Parameters[0].GetValue(record).ToString(), out d);
                if (success)
                {
                    return Math.Round(d);
                }
                else
                {
                    return null;
                }
            }
            else if (Parameters.Count == 2) 
            {
                decimal d;
                int decimals;

                bool success = Decimal.TryParse(Parameters[0].GetValue(record).ToString(), out d);
                if (success)
                {
                    success = Int32.TryParse(Parameters[1].GetValue(record).ToString(), out decimals);
                    if (success)
                    {
                        return Math.Round(d, decimals);
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            else
            {
                throw new NotImplementedException("Round function can't accept more than two parameters.");
            }
        }
    }
}
